package com.example.demo.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.session.Book;
import com.example.demo.entity.session.DB;
import io.swagger.annotations.ApiOperation;


@RestController
@RequestMapping("/session")
@CrossOrigin
public class SessionController {

    @ApiOperation(value = "验证session唯一性的问题")
    @GetMapping(value = "/one/request")
    public void sessionOneRequest(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //使用request对象的getSession()获取session，如果session不存在则创建一个
        HttpSession session = request.getSession();
        //将数据存储到session中
        session.setAttribute("data", "唯一性");
        //获取session的Id
        String sessionId = session.getId();
        //判断session是不是新创建的
        if (session.isNew()) {
            try {
                response.getWriter().print("session创建成功，session的id是："+sessionId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                response.getWriter().print("服务器已经存在该session了，session的id是："+sessionId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ;
    }
    @ApiOperation(value = "cookie禁用验证")
    @GetMapping(value = "/disable/request")
    public void cookieDisableRequest(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //使用request对象的getSession()获取session，如果session不存在则创建一个
        HttpSession session = request.getSession();
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        out.write("本网站有如下书：<br/>");
        Set<Map.Entry<String, Book>> set = DB.getAll().entrySet();
        for(Map.Entry<String,Book> me : set){
            Book book = me.getValue();
            String url =request.getContextPath()+ "/user/request?id=" + book.getId();
            //response. encodeURL(java.lang.String url)用于对表单action和超链接的url地址进行重写
            url = response.encodeURL(url);//将超链接的url地址进行重写
            out.println(book.getName()  + "   <a href='"+url+"'>购买</a><br/>");
        }
    }

}
